package my.senix.sc.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

/**
 * Created by lhs on 2018/11/6.
 */
@RestController
public class DeferredController {


    @GetMapping("/defer")
    public DeferredResult<String> getDelayResult() {
        DeferredResult<String> dr = new DeferredResult(36*1000L);


        new Thread(() -> {

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            dr.setResult("deferred is ok");
//            dr.setErrorResult("故意这个泡个错误");
//            dr.setErrorResult(new Th("这个是一个错了无"));
        }).start();

        dr.onTimeout(() -> {
            dr.setResult("time out");
            System.out.println("time out");
        });

        dr.onCompletion(() -> {
            System.out.println("complete: isSetOrExpiredd: " + dr.isSetOrExpired());
            dr.setResult("complete");
        });

        dr.onError((e) -> {
            System.out.println("报错啦：");
            e.printStackTrace();

            System.out.println("error: isSetOrExpiredd: " + dr.isSetOrExpired());
            dr.setResult(e.getMessage());
        });


        return dr;
    }
}
